<?php
class Properties extends MY_Controller{

	function __construct(){
		parent::__construct();

		if(!$this->checkUserStatus()){
			redirect('login');
		}else{
			$this->aauth->update_activity();
		}

	}



	function index(){
		$data['toDoList'] = $this->get_tasks();
		$data['customers'] = customer::find('all');
		$data['properties'] = property::find('all');
		$data['title'] = $this->title('Fiche des Biens');
		$data['user'] = $this->aauth->get_user();
		$this->load->view($this->theme.'/header',$data);
		$this->load->view($this->theme.'/properties/index');
		$this->load->view($this->theme.'/footer');

			
	}


	function modification(){

		if(!$_POST){
			redirect("error_404");
		}else{

			$pk = $_POST['pk'];
			$name = $_POST['name'];
			if($name == 'surface' || $name == 'price' || $name=="commission"){
				$value = $this->tofloat($_POST['value']);
			}else{
				$value = $_POST['value'];
			}

			if(!empty($value) || ($name != 'number' && $name !='address' && $name != 'city' && $name != 'po')) {

				$item = property::find_by_id($pk);
				$item->$name = $value;
				$item->save();
				header('HTTP 200 OK', true, 200);
				echo $name;
			} else {

				header('HTTP 400 Bad Request', true, 400);
				echo "Ce champ est obligatoire!";
			}
		}

	}



	function addNewProperty ($client_id=null){
		$this->load->library('form_validation');
		$this->form_validation->set_rules('num',"numéro", "required");
		$this->form_validation->set_rules('address',"adresse", "required");
		$this->form_validation->set_rules('po',"code postal", "required");
		$this->form_validation->set_rules('city',"ville", "required");
		$this->form_validation->set_error_delimiters('<p class="text-red">', '</p>');
		$this->form_validation->set_message('rule', 'Error Message');
		if($_POST){
			if($this->form_validation->run()==false){

			}else{
				$category_id = $_POST['category'];
				$number = $_POST['num'];
				$address = $_POST['address'];
				$po = $_POST['po'];
				$city = $_POST['city'];
				$pobox = $_POST['pobox'];
				$floor = $_POST['floor'];
				$surface = $_POST['surface'];
				$price = $_POST['price'];
				$flash = $_POST['comment'];
				$country = $_POST['country'];
					
				$data = array('id'=>'', 'address'=>$address,'number'=>$number, 'pobox'=>$pobox,'floor'=>$floor,'po'=>$po,'city'=>$city,'category_id'=>$category_id,'price'=>$price,'surface'=>$surface,'flash'=>$flash,'date_create'=>date('Y-m-d H:i:s'),'country'=>$country);

				$newProperty = property::create($data);
				if($newProperty){
					redirect('properties/viewProperty/'.$newProperty->id);
				}else{
					$data['errors'] = array('il y a une erreur');
				}
			}
		}
		//$data['customers'] = customer::find('all');
		$data['toDoList'] = $this->get_tasks();
		$data['title'] = $this->title('Fiche des Biens');
		$data['user'] = $this->aauth->get_user();
		$data['category'] = category::find('all');
		$this->load->view($this->theme.'/header',$data);
		$this->load->view($this->theme.'/properties/addNewProperty');
		$this->load->view($this->theme.'/footer');

	}


	function viewProperty ($id = null){	$this->load->library('encrypt');
	$this->load->library('form_validation');
	if($_POST){
			
		if($_POST['type'] =='transaction'){
			$this->form_validation->set_rules('date',"date", "required");
			$this->form_validation->set_error_delimiters('<p class="text-red">', '</p>');
			$this->form_validation->set_message('rule', 'Error Message');
			if($this->form_validation->run() ==false){

			}else{
				$key = 'dfsghjkhljkjhg';
				$id = $this->encrypt->encode($_POST['date'], $key);
				$date = date("Y-m-d",strtotime($_POST['date']));

				$data = array('id'=>$id,'date'=>$date,'procedure_id'=>$_POST['procedure_id'],'property_id'=>$_POST['property_id'],'flash'=>$_POST['flash']);
				//var_dump($data);
				$newTransaction = historical::create($data);
				if($newTransaction){
					redirect('properties/viewProperty/'.$newTransaction->property_id);
				}else{
					$data['msg_error'] = "il y a une erreur...";
				}
			}
		}else{
			$this->form_validation->set_rules('start_date',"début d'événement", "required");
			$this->form_validation->set_rules('content',"détailles d'événement", "required");
			$this->form_validation->set_error_delimiters('<p class="text-red">', '</p>');
			$this->form_validation->set_message('rule', 'Error Message');
			if($this->form_validation->run() ==false){

			}else{

				$key = 'dfsghjkhljkjhg';
				$id = $this->encrypt->encode($_POST['content'], $key);
				$start_date = date("Y-m-d H:i:s",strtotime($_POST['start_date']));
				if($_POST['end_date'] == ''){
					$end_date = date("Y-m-d H:i:s",strtotime($_POST['start_date'].'+1 hours'));
				}else{
					$end_date = date("Y-m-d H:i:s",strtotime($_POST['end_date']));
				}
				$data = array('id'=>$id,'date_start'=>$start_date,'date_end'=>$end_date,'content'=>$_POST['content'],'property_id'=>$_POST['property_id'],'aauth_user_id'=>$_POST['agent_id'],'color'=>$_POST['color']);
				$newEvent = follow::create($data);
				if($newEvent){
					redirect('properties/viewProperty/'.$newEvent->property_id);
				}else{
					$data['msg_error'] = "il y a une erreur...";
				}

			}
		}
	}
	if($id == null || !$this->check_property_exsite($id)){
		redirect('properties');
	}
	$data['toDoList'] = $this->get_tasks();
	$doList = follow::find('all',array('conditions'=>array('property_id= ? AND aauth_user_id = ? AND date_start > ?',$id,$this->aauth->get_user_id(),date('Y-m-d ')),'order'=>'date_start asc'));
	$data['doList'] = $doList;
	$data['imgs'] = photo::find('all',array('conditions'=>array('property_id'=>$id)));
	$property = property::find_by_id($id);
	$data['property'] = $property;
	$procedures = procedure::find('all');
	$data['procedures'] = $procedures;
	$transactions = historical::find('all',array('conditions'=>array('property_id'=>$id),'order'=>'date desc'));
	$data['transactions'] = $transactions;
	$data['agent'] = aauth_user::find_by_id($property->aauth_user_id);
	$data['customers'] = customer::find('all');
	$data['title'] = $this->title('Fiche des Biens');
	$data['user'] = $this->aauth->get_user();
	$data['category'] = category::find('all');
	$this->load->view($this->theme.'/header',$data);
	$this->load->view($this->theme.'/properties/viewProperty');
	$this->load->view($this->theme.'/footer');


	}

	function PropertiesData(){


		$this->load->library('Datatables');
		 if($this->aauth->is_admin()){
		$this->datatables
		->select(' properties.id AS id  , properties.address as address, number, pobox, floor, po, city, price, surface , flash')
		->from('properties')
		->join('categories', 'properties.category_id = categories.id','left outer')
		->select('category,categories.id as category_id')
		->join('customers', 'properties.customer_id = customers.id','left outer')
		->select('firstname, ,lastname,customers.id as customer_id')
		->join('aauth_users', 'properties.aauth_user_id = aauth_users.id','left outer')
		->select('name, aauth_users.id as agent_id')
		->join('contracts', 'properties.contract_id = contracts.id','left outer')
		->select('contract, contracts.id as contract_id')
		->join('transactions', 'properties.transaction_id = transactions.id','left outer')
		->select('deal, transactions.id as transaction_id')
		->edit_column('address', '- <a href="#" id="number"  data-type="text" data-pk="$1" data-url="'.site_url().'properties/modification" data-title="Num" class="allowEdit">$3</a> - <a href="#" id="address"  data-type="textarea" data-pk="$1" data-url="'.site_url().'properties/modification" data-title="Adresse" class="allowEdit">$2</a>', 'id,address,number')
		->edit_column('pobox', '<a href="#" id="pobox"  data-type="text" data-pk="$1" data-url="'.site_url().'properties/modification" data-title="Boîte" class="allowEdit">$2</a>', 'id,pobox')
		->edit_column('floor', '<a href="#" id="floor"  data-type="text" data-pk="$1" data-url="'.site_url().'properties/modification" data-title="Etage" class="allowEdit">$2</a>', 'id,floor')
		->edit_column('po', '<a href="#" id="po"  data-type="text" data-pk="$1" data-url="'.site_url().'properties/modification" data-title="Code Postal" class="allowEdit">$2</a>', 'id,po')
		->edit_column('city', '<a href="#" id="city"  data-type="text" data-pk="$1" data-url="'.site_url().'properties/modification" data-title="Commune" class="allowEdit">$2</a>', 'id,city')
		->edit_column('price', '<a href="#" id="price"  data-type="text" data-pk="$1" data-url="'.site_url().'properties/modification" data-title="Prix" class="allowEdit">$2</a> €', 'id,price')
		->edit_column('surface', '<a href="#" id="surface"  data-type="text" data-pk="$1" data-url="'.site_url().'properties/modification" data-title="Superficie" class="allowEdit">$2</a> M&sup2;', 'id,surface')
		->edit_column('flash', '<a href="#" id="flash"  data-type="textarea" data-pk="$1" data-url="'.site_url().'properties/modification" data-title="Superficie" class="allowEdit">$2</a>', 'id,flash')
		->edit_column('category','<a href="#" id="category_id" data-prepend="non spécifié" data-type="select" data-pk="$1" data-value="$3" data-url="'.site_url().'properties/modification" data-source="'.site_url().'properties/selectData/category" class="allowEdit">$2</a>','id,category,category_id')
		->edit_column('customer','<a href="#" id="customer_id" data-prepend="non spécifié" data-type="select" data-pk="$1" data-value="$4" data-url="'.site_url().'properties/modification" data-source="'.site_url().'properties/selectData/customer" class="allowEdit">$2 $3</a>','id,lastname,firstname,customer_id')
		->edit_column('agent','<a href="#" id="aauth_user_id" data-prepend="non spécifié" data-type="select" data-pk="$1" data-value="$2" data-url="'.site_url().'properties/modification" data-source="'.site_url().'properties/selectData/agent" class="allowEdit">$3</a>','id,agent_id,name')
		->edit_column('contract','<a href="#" id="contract_id" data-prepend="non spécifié" data-type="select" data-pk="$1" data-value="$3" data-url="'.site_url().'properties/modification" data-source="'.site_url().'properties/selectData/contract" class="allowEdit">$2</a>','id,contract,contract_id')
		->edit_column('transaction','<a href="#" id="transaction_id" data-prepend="non spécifié" data-type="select" data-pk="$1" data-value="$3" data-url="'.site_url().'properties/modification" data-source="'.site_url().'properties/selectData/transaction" class="allowEdit">$2</a>','id,deal,transaction_id')
		->add_column('actions', '<a class="btn btn-xs btn-primary" href="' . site_url() . 'properties/viewProperty/$1"><i class="fa fa-eye"></i> voir</a> | <a class="btn btn-xs btn-danger" href="#" onclick="deleteProperty($1)"><i class="fa fa-trash-o"></i> supprimer</a>', 'id')
		;
		 }else{
		 	$this->datatables
		->select(' properties.id AS id  , properties.address as address, number, pobox, floor, po, city, price, surface , flash')
		->from('properties')
		->join('categories', 'properties.category_id = categories.id','left outer')
		->select('category,categories.id as category_id')
		->join('customers', 'properties.customer_id = customers.id','left outer')
		->select('firstname, ,lastname,customers.id as customer_id')
		->join('aauth_users', 'properties.aauth_user_id = aauth_users.id','left outer')
		->select('name, aauth_users.id as agent_id')
		->join('contracts', 'properties.contract_id = contracts.id','left outer')
		->select('contract, contracts.id as contract_id')
		->join('transactions', 'properties.transaction_id = transactions.id','left outer')
		->select('deal, transactions.id as transaction_id')
		->edit_column('address', '- <a href="#" id="number"  data-type="text" data-pk="$1" data-url="'.site_url().'properties/modification" data-title="Num" class="allowEdit">$3</a> - <a href="#" id="address"  data-type="textarea" data-pk="$1" data-url="'.site_url().'properties/modification" data-title="Adresse" class="allowEdit">$2</a>', 'id,address,number')
		->edit_column('pobox', '<a href="#" id="pobox"  data-type="text" data-pk="$1" data-url="'.site_url().'properties/modification" data-title="Boîte" class="allowEdit">$2</a>', 'id,pobox')
		->edit_column('floor', '<a href="#" id="floor"  data-type="text" data-pk="$1" data-url="'.site_url().'properties/modification" data-title="Etage" class="allowEdit">$2</a>', 'id,floor')
		->edit_column('po', '<a href="#" id="po"  data-type="text" data-pk="$1" data-url="'.site_url().'properties/modification" data-title="Code Postal" class="allowEdit">$2</a>', 'id,po')
		->edit_column('city', '<a href="#" id="city"  data-type="text" data-pk="$1" data-url="'.site_url().'properties/modification" data-title="Commune" class="allowEdit">$2</a>', 'id,city')
		->edit_column('price', '<a href="#" id="price"  data-type="text" data-pk="$1" data-url="'.site_url().'properties/modification" data-title="Prix" class="allowEdit">$2</a> €', 'id,price')
		->edit_column('surface', '<a href="#" id="surface"  data-type="text" data-pk="$1" data-url="'.site_url().'properties/modification" data-title="Superficie" class="allowEdit">$2</a> M&sup2;', 'id,surface')
		->edit_column('flash', '<a href="#" id="flash"  data-type="textarea" data-pk="$1" data-url="'.site_url().'properties/modification" data-title="Superficie" class="allowEdit">$2</a>', 'id,flash')
		->edit_column('category','<a href="#" id="category_id" data-prepend="non spécifié" data-type="select" data-pk="$1" data-value="$3" data-url="'.site_url().'properties/modification" data-source="'.site_url().'properties/selectData/category" class="allowEdit">$2</a>','id,category,category_id')
		->edit_column('customer','<a href="#" id="customer_id" data-prepend="non spécifié" data-type="select" data-pk="$1" data-value="$4" data-url="'.site_url().'properties/modification" data-source="'.site_url().'properties/selectData/customer" class="allowEdit">$2 $3</a>','id,lastname,firstname,customer_id')
		->edit_column('agent','<a href="#" id="aauth_user_id" data-prepend="non spécifié" data-type="select" data-pk="$1" data-value="$2" data-url="'.site_url().'properties/modification" data-source="'.site_url().'properties/selectData/agent" class="allowEdit">$3</a>','id,agent_id,name')
		->edit_column('contract','<a href="#" id="contract_id" data-prepend="non spécifié" data-type="select" data-pk="$1" data-value="$3" data-url="'.site_url().'properties/modification" data-source="'.site_url().'properties/selectData/contract" class="allowEdit">$2</a>','id,contract,contract_id')
		->edit_column('transaction','<a href="#" id="transaction_id" data-prepend="non spécifié" data-type="select" data-pk="$1" data-value="$3" data-url="'.site_url().'properties/modification" data-source="'.site_url().'properties/selectData/transaction" class="allowEdit">$2</a>','id,deal,transaction_id')
		 ->add_column('actions', '<a class="btn btn-xs btn-primary" href="' . site_url() . 'properties/viewProperty/$1"><i class="fa fa-eye"></i> voir</a> ', 'id');
		 }
		


		$result = $this->datatables->generate('json','utf8');
		//$result2 = $this->datatables->generate('json');
		$result = str_replace(array("\r\n", "\n", "\r"), ' ',$result);
		echo $result;
		//	echo '<hr>';
		//	echo json_encode($result2);
		//$this->load->view($this->theme.'/footer');


	}

	function get_extraData(){
		if(!$_POST){
			redirect('error_404');
		}else{
			$photos = photo::find('all',array('conditions'=>array('property_id='.$_POST['id'])));
			$lists = follow::find('all', array('conditions'=>array('property_id = ? AND aauth_user_id = ? AND date_start > ?',$_POST['id'],$this->aauth->get_user_id(),date('Y-m-d') ),'order'=>'date_start asc'));
			$transactions = historical::find('all',array('conditions'=>array('property_id='.$_POST['id']),'order'=>'date desc'));
			if($photos){
				$pt = array();
				foreach ($photos as $p){
					$file_l = base_url().'uploads/large/'.$p->filename_l;
					$file_s = base_url().'uploads/thumbs/'.$p->filename_s;

					$pt[]= array('file_l'=>$file_l,'file_s'=>$file_s);
				};
			}else{
				$pt = null;
			}

			if($lists){
				$toDoList = array();
				foreach ($lists as $l){
					$toDoList[] = array('content'=>$l->content,'date_start'=>date('d-m-Y H:i',strtotime($l->date_start)),'color'=>$l->color);
				}
			}else{
				$toDoList = null;
			}
			
			if($transactions){
				$trans = array();
				foreach ($transactions as $t){

					$trans[]= array('procedure'=>$t->procedure->procedure,'flash'=>$t->flash,'date'=>date('d-M-Y',strtotime($t->date)));
				};
			}else{
				$trans = null;
			}
			$data = array('photos'=>$pt,'toDoList'=>$toDoList,'transactions'=>$trans);
			echo  json_encode($data);

		}
	}

	function deleteItem(){
		if($_POST){

			$id =$_POST['id'];
			$deleteItem = photo::find_by_id($id);
			if($deleteItem->delete()){
				$reposition = photo::find('all',array('conditions'=>array('position'=>$deleteItem->position)));
				if($reposition):
				foreach ($reposition as $res){
					$res->position = $res->position-1;
					$res->save();
				}
				endif;
					
				/* check existe files */
				$l = get_file_info('uploads/large/'.$deleteItem->filename_l);
				$m = get_file_info('uploads/medium/'. $deleteItem->filename_m);
				$s = get_file_info('uploads/thumbs/'. $deleteItem->filename_s);
				if($l){
					unlink(FCPATH.'uploads/large/'.$deleteItem->filename_l);
				}
				if($m){
					unlink(FCPATH.'uploads/medium/'.$deleteItem->filename_m);
				}
				if($s){
					unlink(FCPATH.'uploads/thumbs/'.$deleteItem->filename_s);
				}
				/* end of check existe files */

				echo json_encode(array('result'=>true));
			}else{
				echo json_encode(array('result'=>false));
			}

		}else{
			redirect('properties');
		}
	}


	function deleteTrans(){
		if(!$_POST){
			redirect('error_404');
		}else{
			$id = $_POST['id'];
			$deleteItem = historical::find_by_id($id);
			//echo json_encode($deleteItem);
			if($deleteItem){
				$deleteItem->delete();
				echo json_encode(true) ;
			}else{
				echo json_encode(true);
			}
		}
	}
	
	
	function deleteEvent(){
		if(!$_POST){
			redirect('error_404');
		}else{
			$id = $_POST['id'];
			$deleteItem = follow::find_by_id($id);
			//echo json_encode($deleteItem);
			if($deleteItem){
				$deleteItem->delete();
				echo json_encode(true) ;
			}else{
				echo json_encode(true);
			}
		}
	}

	function deleteProperty(){
		if(!$_POST){
			redirect('error_404');
		}else{
			$id = $_POST['id'];
			$deleteItem = property::find_by_id($id);
			if($deleteItem){
				$deleteItem->delete();
				echo json_encode(true) ;
			}else{
				echo json_encode(true);
			}
		}
	}

	function selectData($item = null){
		if($item == null)
		redirect('error_404');

		$data = $this->get_selectData($item);

		if($data){
			echo json_encode($data);
		}else{
			header('HTTP 400 Bad Request', true, 400);
			echo "Interne Errors !";
		}

	}


	function addContact(){
		if(!$_POST){
			redirect('error_404');
		}else{
			$data = array('firstname'=>$_POST['firstname'],'lastname'=>$_POST['lastname'],'lang_id'=>1,'date_create'=>date('Y-m-d H:i:s'));
			$newContact = customer::create($data);
			if($newContact){
				$property = property::find_by_id($_POST['property_id']);
				$property->customer_id = $newContact->id;
				$property->save();
				echo json_encode(true);
			}else{
				echo json_encode(false);
			}

		}
	}



	private function check_property_exsite($id){

		$p = property::find_by_id($id);
		if($p)
		return true;
		else
		return false;

	}





	private function get_selectData($item)
	{
		$d = array();

		switch ($item):

		case 'category':
			$data = category::find('all');
			foreach ($data as $i){
				$d[] = array('value'=>$i->id,'text'=>$i->category);
			}
			break;
		case 'agent':
			$data = agent::find_by_sql('SELECT * FROM `agents` INNER JOIN `aauth_users` ON(`agents`.aauth_user_id = `aauth_users`.id)');
			foreach ($data as $i){
				$d[] = array('value'=>$i->id,'text'=>$i->name);
			}
			break;

		case 'customer':
			$data = customer::find('all',array('order'=>'lastname asc'));
			foreach ($data as $i){
				$d[] = array('value'=>$i->id,'text'=>$i->lastname.' '.$i->firstname);
			}
			break;

		case 'contract':
			$data = contract::find('all');
			foreach ($data as $i){
				$d[] = array('value'=>$i->id,'text'=>$i->contract);
			}
			break;

		case 'statut':
			$data = statut::find('all');
			foreach ($data as $i){
				$d[] = array('value'=>$i->id,'text'=>$i->statut);
			}
			break;
		case 'transaction':
			$data = transaction::find('all');
			foreach ($data as $i){
				$d[] = array('value'=>$i->id,'text'=>$i->deal);
			}
			endswitch;

			return $d;
	}






}